﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Dungeon_Dive
{
    public class AnimModel : DrawableGameComponent
    {
        private bool playOnce;
        private bool stopped;
        public bool Stopped { get { return stopped; } }

        private int currentFrame;
        public int CurrentFrame { get { return currentFrame; } }

        private String currentAnim;
        public String CurrentAnim { get { return currentAnim; } set { currentAnim = value; currentFrame = 0; } }

        public Model Model { get { return anims[currentAnim][currentFrame]; } }

        private Dictionary<String, List<Model>> anims;
        private TimeSpan frameDelay;  //Milliseconds
        public TimeSpan FrameDelay 
        { 
            get { return frameDelay; } 
            set 
            {
                if (value == TimeSpan.Zero) value = TimeSpan.FromMilliseconds(1);
                frameDelay = value;
            } 
        }
        private TimeSpan elapsedTime;

        public AnimModel(Game game) : base (game)
        {
            anims = new Dictionary<string, List<Model>>();
            stopped = true;
            frameDelay = TimeSpan.FromMilliseconds(100);
        }

        public void AddFrame(String anim, Model newFrame)
        {
            if (!anims.ContainsKey(anim))
            {
                anims.Add(anim, new List<Model>());
            }
            anims[anim].Add(newFrame);
        }

        public override void Update(GameTime gameTime)
        {
            if (!stopped)
            {
                elapsedTime += gameTime.ElapsedGameTime;
                if (elapsedTime > frameDelay)
                {
                    ++currentFrame;
                    if (currentFrame >= anims[currentAnim].Count)
                    {
                        currentFrame = 0;
                        if (playOnce)
                        {
                            stopped = true;
                            playOnce = false;
                        }
                    }
                    elapsedTime -= frameDelay;
                }
            }
            base.Update(gameTime);
        }

        public void Play() { stopped = !stopped; }
        public void Stop() { stopped = true; currentFrame = 0; }

        public override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);
        }

        public void PlayOnce(String anim)
        {
            currentAnim = anim;
            currentFrame = 0;
            playOnce = true;
            stopped = false;
        }

        public int FrameCount(String anim)
        {
            return anims[anim].Count;
        }
    }
}
